package com.irs.irsforum.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.irs.irsforum.entity.Message;
import com.irs.irsforum.entity.Record;
import com.irs.irsforum.entity.User;
import com.irs.irsforum.mapper.BehaviorMapper;
import com.irs.irsforum.mapper.MessageMapper;
import com.irs.irsforum.mapper.PostMapper;
import com.irs.irsforum.mapper.RecordMapper;
import com.irs.irsforum.mapper.StudentMapper;
import com.irs.irsforum.mapper.UserMapper;
import com.irs.irsforum.service.IMessageService;
import com.irs.irsforum.utils.RecommendAlgorithm;
import com.irs.irsforum.utils.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yihuili
 * @since 2020-02-12
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {
    private static final Logger logger =
            LoggerFactory.getLogger(MessageServiceImpl.class);

    @Autowired
    MessageMapper messageMapper;
    @Autowired
    StudentMapper studentMapper;
    @Autowired
    RecordMapper recordMapper;
    @Autowired
    PostMapper postMapper;
    @Autowired
    BehaviorMapper behaviorMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public List<Message> getMessageList(Long userId) {
        List<Message> messageList = messageMapper.getMessageList(userId);
        if (messageList != null && messageList.size() > 0) {
            messageList.stream().forEach(item -> item.setRecipientNickName(getNickName(item.getRecipient())));
            messageList.stream().forEach(item -> item.setSenderNickName(getNickName(item.getSender())));
        }
        return messageList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer setRead(Long userId, Long messageId) {
        Integer result = messageMapper.setRead(userId, messageId);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer delMessage(Long userId, Long messageId) {
        Integer result = messageMapper.delMessage(userId, messageId);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer writeRecommendMessage(Message message, Long problemId, Long subjectId) throws SQLException {
        Integer result;
        if (message.getPostId() == null) {
            logger.error("postId为null");
            return 0;
        } else {
            try {
                List<Long> studentList = RecommendAlgorithm.messageRecommend(problemId, subjectId, message.getSender());
                if (studentList == null || studentList.size() <= 0) {
                    logger.error("推荐列表为空，不进行消息推荐");
                    return 0;
                }
                message.setRecommendStudentList(studentList);
                message.setCreationTime(TimeUtil.getSqlTime());
                result = messageMapper.writeMessage(message);
            } catch (Exception e) {
                logger.error(e.getMessage());
                throw new SQLException();
            }
        }
        return result;
    }


    /**
     * 记录了正确率，备用
     *
     * @param records
     * @param correctRank
     * @param studentList
     */
    public void setList1(List<Record> records, Map<Long, Double> correctRank, List<Long> studentList) {
        for (Record record : records) {
            if (correctRank.size() == 5) {
                break;
            }
            studentList.add(record.getStuId());
            correctRank.put(record.getStuId(), 1.0 / (record.getInCorrects() + 1));
        }
    }


    public String getNickName(Long userId) {
        User user = userMapper.getUserById(userId);
        if (user != null) {
            return user.getNickName();
        }
        return "";
    }
}
